//
//  RootViewController.m
//  ws-mgmt-client
//
//  Created by Cliff Duffey on 9/14/09. Mage Labs.
//

#import "RootViewController.h"
#import "ConfigureServerViewController.h"
#import "ws_mgmt_clientAppDelegate.h"
#import "ServerEventsViewController.h"
#import "NSStringAdditions.h"
#import "ServerRootViewController.h"
#import "Reachability.h"

@implementation RootViewController
@synthesize serverList, inRoot;

#pragma mark Support methods
//Returns a string that contains the path to the file that the data is stored in
- (NSString *)dataFilePath
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	return [documentsDirectory stringByAppendingPathComponent:kFilename];
}

//Function is called to add a server object
- (void) addServer: (NSMutableDictionary *)server atIndex: (NSUInteger) index
{	
	NSLog(@"in addServer: %@", [server objectForKey:@"URL"]);
	
	if( index >= [serverList count] )
		[serverList addObject: server];
	else
		[serverList replaceObjectAtIndex:index withObject:server];
	
	NSLog(@"New serverList count: %d", [serverList count]); 

}

//Function is called when the reload button is pressed. Will refresh the table.
- (IBAction) reloadButton: (id) sender
{
	[self.tableView reloadData];
}

//Function is called when the add button is pressed. Will push the Configure Table view on the Nav stack
- (IBAction) addButton: (id) sender
{
	// Navigation logic to push the ConfigureServerViewContoller view controller.
	ConfigureServerViewController *configureServerViewController = [[ConfigureServerViewController alloc] initWithNibName:@"ConfigureServerViewController" bundle:nil];
	configureServerViewController.isNewServer = YES;
	configureServerViewController.listIndex = [serverList count];  
	
	self.inRoot = TRUE; //Tell ConfigureItemView that we're coming from the RootView
	
	NSLog(@"About to push ConfigureServer on nav view stack");
	
	ws_mgmt_clientAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	[delegate.navigationController pushViewController:configureServerViewController animated:YES]; 
	
	[configureServerViewController release];
	
}

#pragma mark View methods

- (void)viewDidLoad {
    [super viewDidLoad];
	
	NSString *filePath = [self dataFilePath];
	NSMutableArray * array;
	
	self.inRoot = TRUE; //initialize inRoot
	
	//Get the contents of the file (if it exists) and put it into our server array
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
		array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
	}
	else array = [[NSMutableArray alloc] init];
	
	self.serverList = array;
	[array release];
	
	//Register our function to write out the array when the application terminates
	UIApplication *app = [UIApplication sharedApplication];
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(applicationWillTerminate:)
												 name:UIApplicationWillTerminateNotification 
											   object:app];
	
	//Set the title of the window to 'Server List'
	self.title = @"Server List";
	
	//Add a system 'Add' button to the right
	UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
                                  initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addButton:)];	
	self.navigationItem.rightBarButtonItem = addButton;
	[addButton release];
	
	//Add a system 'Reload' button to the left
	UIBarButtonItem *reloadButton = [[UIBarButtonItem alloc]
                                  initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(reloadButton:)];	
	self.navigationItem.leftBarButtonItem = reloadButton;
	[reloadButton release];
	
	//Check if we can reach our default gateway
	NetworkStatus netStatus;
	
    wifiReach = [[Reachability reachabilityForLocalWiFi] retain];
	[wifiReach startNotifer];
	netStatus = [wifiReach currentReachabilityStatus];
	if( netStatus == NotReachable )
	{
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Network Error" 
														message:@"No Wi-Fi detected. Network connectivity may be limited." 
													   delegate:nil 
											  cancelButtonTitle:@"Close" 
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
	} else {
		internetReach = [[Reachability reachabilityForInternetConnection] retain];
		[internetReach startNotifer];
		netStatus = [internetReach currentReachabilityStatus];
		if( netStatus == NotReachable )
		{
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Network Error" 
															message:@"Can't reach gateway. Network connectivity may be limited." 
														   delegate:nil 
												  cancelButtonTitle:@"Close" 
												  otherButtonTitles:nil];
			[alert show];
			[alert release];
		} 
	}

}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

- (void)applicationWillTerminate:(NSNotification *)notification
{
	NSString *filePath = [self dataFilePath];
	[serverList writeToFile: filePath atomically:YES];
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.serverList count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"RootViewCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Set up the cell...
	if( [serverList count] > 0 )
	{
		NSUInteger index = [indexPath row]; //index of the array to be accessed
		NSMutableDictionary *server = [serverList objectAtIndex:index];
		
		cell.textLabel.text = [server valueForKey:@"Name"];
	/*	
		NSString *hostURL = [server valueForKey:@"URL"];
		NSArray *listItems = [hostURL componentsSeparatedByString:@"/"];
		NSString *hostAddress = (NSString *)[listItems objectAtIndex:2];
		NSLog(@"hostAddress = %@", hostAddress);
		
		NetworkStatus netStatus;

		hostReach = [[Reachability reachabilityWithHostName: hostAddress] retain];		
		[hostReach startNotifer];
		netStatus = [hostReach currentReachabilityStatus];
		if( netStatus == NotReachable )
		{
			cell.imageView.image = [UIImage imageNamed:@"red.png"];
		} else {
			cell.imageView.image = [UIImage imageNamed:@"green.png"];
		}	
		[hostURL release];
	 */
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	 
	}

    return cell;
}

//Delete a row (server) when gestered
- (void) tableView: (UITableView *) tableView
commitEditingStyle: (UITableViewCellEditingStyle) editingStyle
 forRowAtIndexPath: (NSIndexPath *) indexPath {
	
	NSUInteger row = [indexPath row];
	[self.serverList removeObjectAtIndex: row];
	[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject: indexPath] withRowAnimation: UITableViewRowAnimationFade];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSDictionary *selectedServer = (NSDictionary *)[self.serverList objectAtIndex: [indexPath row]];
	
	// Navigation logic to push the ConfigureServerViewContoller view controller.

	ServerRootViewController *serverRootViewController = [ServerRootViewController alloc];
	serverRootViewController.server = selectedServer; //Pass info on the selected server to the new view controller
	[serverRootViewController initWithNibName:@"ServerRootViewController" bundle:nil];
	
	if( serverRootViewController.server == NULL )
		NSLog(@"Server is empty!\n");
	else {
		NSLog(@"%@", [serverRootViewController.server objectForKey:@"URL"]);
	}

	self.inRoot = FALSE; //Since we're going into ServerRoot, tell ConfigureItem that we're no longer in Root
	serverRootViewController.serverListIndex = [indexPath row];
	ws_mgmt_clientAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	[delegate.navigationController pushViewController:serverRootViewController animated:YES]; 	
    [serverRootViewController release];	
 
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


- (void)dealloc {
    [super dealloc];
}


@end

